#!/usr/bin/perl -w
 
use warnings;
use strict;
use POE;
use POE::Component::Server::TCP;

my $ESECACHE_DATA = {};
my $port = 11213;

POE::Component::Server::TCP->new(
     Port               => $port,
     ClientConnected    => \&handle_client_connect,
     ClientInput        => \&client_input,
     ClientFlushed      => \&handle_client_flush,   
#     InlineStates       => {
#         send_response => \&send_response,
#     },
     Concurrency        => -1,
    );
 
POE::Kernel->run;
exit;


sub handle_client_connect{
    my ($kernel, $heap, $input) = @_[KERNEL, HEAP, ARG0];
    my $id = $heap->{client}->ID;
    $heap->{'input_buff'.$id} = [''];
}
 
sub handle_client_flush {
    my ( $heap, $input ) = @_[HEAP, ARG0];
}

sub client_input {
    my ($kernel, $heap, $input) = @_[KERNEL, HEAP, ARG0];
    my $id = $heap->{client}->ID;
    my $input_buff = $heap->{'input_buff'.$id};

    if( $input =~ /^set\ (\S+)\ \d+\ \d+\ \d+/i ){

    }
    elsif( $input_buff->[0] =~ /^set\ (\S+)\ \d+\ \d+\ \d+/i ){
        my $key = $1;
        $ESECACHE_DATA->{$key} = $input;
        $heap->{client}->put('STORED');
    }
    elsif( $input =~ /^get\ (\S+)/i ){
        my $key = $1;
        my $value = $ESECACHE_DATA->{$key};
        my $l = length($value);
        $heap->{client}->put("VALUE $key 0 $l");
        $heap->{client}->put($value);
        $heap->{client}->put("END");
    }
    elsif( $input =~ /^flush_all/i ){
        $ESECACHE_DATA = {};
        $heap->{client}->put('OK');
    }
    elsif( $input =~ /^delete\ (\S+)/i ){
        my $key = $1;
        if( $ESECACHE_DATA->{$key} ){
            $ESECACHE_DATA->{$key} = '';
            $heap->{client}->put("DELETED");
        }
        else{
            $heap->{client}->put("NOT_FOUND");
        }
    }
    elsif( $input =~ /^quit/i ){
        $heap->{shutdown} = 1;
        $heap->{client}->put("quit");
    }
    else{
        $heap->{client}->put("ERROR");
    }

    unshift @{$heap->{'input_buff'.$id}},$input;
}

__END__

